import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.associationproxy import association_proxy

from cibynet.model import meta
from cibynet.model.m_users_groups import UserGroup
from cibynet.model import tables as t
from cibynet.model import utils
from cibynet.model.utils import UnicodeProperty


class Group(object):
  """Group object. One user may belongs to more than one group.
  Groups have level. The bigger the better!
  """
  users = association_proxy('userassociations', 'user', 
                            creator=lambda u, **kw:UserGroup(user=u, **kw))
  name = UnicodeProperty("_name")
  
  def __init__(self, name, level):
    """
    Arguments:
      - name: string, the name of the group.
      - level: int, the level of the group.
    """
    self.name = name
    self.level = level
    
  def _get_next(self):
    """Returns the smallest but higher level group or None.
    """
    group_q = meta.Session.query(Group).filter("level>%i" % self.level)
    group_q = group_q.order_by("level")
    return group_q.first()
  next = property(_get_next)
  
  def _get_previous(self):
    """Returns the highest but smaller level group or None.
    """
    group_q = meta.Session.query(Group).filter("level<%i" % self.level)
    group_q = group_q.order_by("level").desc()
    return group_q.first()
  previous = property(_get_previous)
    
  def __repr__(self):
    """
    """
    return "Group(%r)" % self.name